#include <REGX52.H>
#include "DS18B20.h"
#include "LCD1602.h"
#include "Delay.h"
#include "Key.h"
#include "Timer0.h"
#include "Timer1.h"

#define TEMP_HIGH	125
#define TEMP_LOW	-55

sbit BZ = P2^5;

int globalTemp;
unsigned char alarmFlag, writeLimitFlag;
char tempHigh, tempLow;

void main() {
	int temp, tmp;
	unsigned char key;
	
	// 读取存储在DS18B20内部EEPROM的温度限制
	tmp = DS18B20_ReadTempLimit();
	tempHigh = tmp >> 8;
	tempLow = tmp & 0x00FF;
	
	LCD_Init();
	LCD_ShowString(1, 1, "T:    .");
	LCD_ShowString(2, 1, "TH:     TL:");
	
	Timer0_Init();
	Timer1_Init();
	
	while (1) {
		temp = globalTemp;
		
		if (temp < 0) {
			temp = -temp;
			LCD_ShowChar(1, 3, '-');
		} else {
			LCD_ShowChar(1, 3, '+');
		}
		
		tmp = temp >> 4;
		
		if (tmp >= tempHigh) {
			alarmFlag = 1;
			LCD_ShowString(1, 13, "OV:H");
		} else if (tmp <= tempLow) {
			alarmFlag = 1;
			LCD_ShowString(1, 13, "OV:L");
		} else {
			alarmFlag = 0;
			LCD_ShowString(1, 13, "    ");
		}
		
		LCD_ShowNum(1, 4, tmp, 3);
		LCD_ShowNum(1, 8, (temp & 0x000F) * 625 / 100, 2);
		
		
		key = Key();
		if (key) {
			switch (key) {
				case 1:
					if (tempHigh < TEMP_HIGH)
						tempHigh++;
					break;
				case 2:
					if (tempHigh > TEMP_LOW && tempHigh > tempLow)
						tempHigh--;
					break;
				case 3:
					if (tempLow < TEMP_HIGH && tempLow < tempHigh)
						tempLow++;
					break;
				case 4:
					if (tempLow > TEMP_LOW)
						tempLow--;
					break;
			}
			
			writeLimitFlag = 1;
		}
		
		LCD_ShowSignedNum(2, 4, tempHigh, 3);
		LCD_ShowSignedNum(2, 12, tempLow, 3);
		
	}
}

void Timer0_Isr(void) interrupt 1
{
	static unsigned int timer0Counter = 0;
	timer0Counter++;
	TL0 = 0x66;
	TH0 = 0xFC;
	
	if (timer0Counter >= 500) {
		timer0Counter = 0;
		// 通过定时器中断来读取温度，因为其它中断会破坏OneWire的时序，造成读取错误
		// 优先级timer0 > timer1
		DS18B20_ConvertT();
		globalTemp = DS18B20_ReadTemp();
		
		// 写入DS18B20的EEPROM
		if (writeLimitFlag) {
			DS18B20_WriteTempLimit(tempHigh, tempLow);
			writeLimitFlag = 0;
		}
	}
}

void Timer1_Isr(void) interrupt 3
{
	static unsigned char timer1Counter = 0;
	timer1Counter++;
	TL1 = 0x66;
	TH1 = 0xFC;
	
	if (timer1Counter >= 20) {
		timer1Counter = 0;
		Key_Scan();
	}
	// P2_5 会与LCD的IO口冲突，此处所以不用蜂鸣器
//	if (alarmFlag)
//		BZ = !BZ;
}